using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;

public class PlayerControl : MonoBehaviour
{
    Rigidbody2D heroBody;
   public float Maxspeed = 10;
    public float Moveforce = 300;
    [HideInInspector]
    public bool bFaceRight = true;
    Transform mGroundCheck;
    bool bGrounded = false;
    [HideInInspector]
    public bool bJump = false;
    public float  JForce=300;
    Animator anim;
    private void Awake()
    {
        mGroundCheck = transform.Find("GroundCheck");
    }
    // Start is called before the first frame update
    void Start()
    {
        heroBody = GetComponent<Rigidbody2D>();
        anim = GetComponent < Animator>();
    }

    // Update is called once per frame

    private void FixedUpdate ()
    {
        float finput = Input.GetAxis("Horizontal");
        if (finput * heroBody.velocity.x < Maxspeed)
        {
            heroBody.AddForce(Vector2.right * finput * Moveforce);
        }
        anim.SetFloat("move", Mathf.Abs(finput));
        if (Mathf.Abs(heroBody.velocity.x) > Maxspeed)
        {
            heroBody.velocity = new Vector2(Mathf.Sign(heroBody.velocity.x) * Maxspeed, heroBody.velocity.y);
        }
        if (finput < 0 && bFaceRight)
            Flip();
        else if (finput > 0 && !bFaceRight)
            Flip();

        if (bJump)
        {
            anim.SetTrigger("jump");
            heroBody.AddForce(new Vector2(0, JForce));
            bJump = false;
        }
    }
    void Flip()
    {
        Vector3 localscale = transform.localScale;
        localscale.x *= -1;
        transform.localScale = localscale;
        bFaceRight = !bFaceRight;
    }
    void Update()
    {
        bGrounded = Physics2D.Linecast(transform.position, mGroundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
        if (bGrounded && Input.GetButtonDown("Jump"))
            bJump = true;
    }

}
